import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_trip_demo/model/gridview_navigator_model.dart';
import 'package:flutter_trip_demo/model/sales_box_model.dart';
import 'package:flutter_trip_demo/pages/search_page.dart';
import 'package:flutter_trip_demo/pages/speaks_page.dart';
import 'package:flutter_trip_demo/utils/navigator/navigator_util.dart';
import 'package:flutter_trip_demo/widght/act_navigator.dart';
import 'package:flutter_trip_demo/widght/grid_navigator.dart';
import 'package:flutter_trip_demo/widght/my_webview.dart';
import 'package:flutter_trip_demo/widght/search_find.dart';

import '../dao/home_dao.dart';
import '../model/common_model.dart';
import '../model/home_model.dart';
import '../widght/bottom_navigator.dart';
import '../widght/local_navigator.dart';

/*
* 设置一个最大值
* */
const APPBAR_SCROLL_OFFSET = 100;
const SEARCH_BAE_TEXT = '网红打卡地 景点 酒店 美食';
///首页模块
//首先改变他的一个状态
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}
/*
* 刘梦洒技术点：banner   首页的一个listview的运用
* 时间点：（2022.7.23）
*
* */

class _HomePageState extends State<HomePage> {
  //每一页的就控制器
  final PageController _controller = PageController(
    initialPage: 0,
  );

  double appBarAlpha = 0;
  String resultString = "";

  List<CommonModel> localNavList = [];
  /*
  首先设置一个空的数据   然后进行添加
  * */
  List<CommonModel> subNavList = [];
  SalesBoxModel? salesBox;
  List<CommonModel> bannerListAppBar = [];

  @override
  void initState() {
    loadData();
    super.initState();
  }


  _onScroll(offset) {
    //滚动的距离/最大值（自己设置一个最大值，判断滑动式是时是否进行滚动）
    //尝试提交
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
  }

  GridNavModel?  gridNavModel;

  Future<Null> loadData() async {
    try {
      HomeModel model = await HomeDao.fetch();
      setState(() {
        localNavList = model.localNavList;
        gridNavModel = model.gridVav;
        subNavList=model.subNavList;
        salesBox = model.salesBox;
        bannerListAppBar = model.bannerList;
      });
    } catch (e) {
      print(e);
    }
  }



  /*
  * 小知识点：
  * Scaffold：脚支架
  * Stack：可以容纳多个组件，以叠加的方式摆放子组件，后者居上。拥有Alignment属性，可以与Positioned组件联合使用，精准并有效摆放。同Android端FramLayout布局相似。
  *NotificationListener：滑动事件分发  当我们给自己的Widget树包裹一层NotificationListener，它就是一个能够处理通知监听的新的Widget了
  *Swiper主要是实现一个轮播的效果
  * */
  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _homesRefresh,
      child: Scaffold(
        backgroundColor: const Color(0xfff2f2f2),
        body: Stack(
          children: <Widget>[
            MediaQuery.removePadding(
              removeTop: true,
              context: context,
              child: NotificationListener(
                  onNotification: (scrollNotification) {
                    if (scrollNotification is ScrollUpdateNotification &&
                        scrollNotification.depth == 0) {
                      _onScroll(scrollNotification.metrics.pixels);
                    }
                    return true;
                  },
                  child: ListView(
                    children: <Widget>[
                      SizedBox(
                          height: 150,
                          child: Swiper(
                            itemCount: bannerListAppBar.length,
                            autoplay: true,
                            itemBuilder: (BuildContext context, int index) {
                              return GestureDetector(
                                onTap: (){
                                  CommonModel model = bannerListAppBar[index];
                                  //使用封跳转工具进行跳转页面
                                  NavigatorUtil.push(
                                    context,
                                    MyWebView(
                                      url: model.url,
                                      statusBarColor: model.statusBarColor,
                                      hideAppBar: model.hideAppBar,
                                    ));
                                },
                                child: Image.network(
                                  bannerListAppBar[index].icon,
                                  fit: BoxFit.fill,
                                ),
                              ) ;
                            },
                            pagination: const SwiperPagination(),
                          )),
                      Padding(padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
                        child: LocalNav(localNavList: localNavList) ,),
                      Padding(padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
                        child: GridNav(gridNavModel: gridNavModel),),
                      Padding(padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
                        child: SubNav(subNavList: subNavList),),
                      Padding(padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
                        child:ActBox(salesBox: salesBox),),
                    ],
                  )),
            ),
            Column(
              children: [
                Container(
                  decoration: const BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Color(0x66000000),Colors.transparent],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ),
                  ),
                  child: Container(
                    padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                    height: 80.0,
                    decoration: BoxDecoration(
                      color: Color.fromRGBO((appBarAlpha*255).toInt(), 255, 255, 255),
                    ),
                    child: SearchFind(
                      searchBarType: appBarAlpha >0.2
                          ? SearchBarTyp.homeLight
                          :SearchBarTyp.home,
                      inputBoxClick: _jumpSearch,
                      speakClick: _jumpSpeak,
                      defaultText: SEARCH_BAE_TEXT,
                      leftButtonClick: (){
                      },
                    ) ,
                  ),
                ),
                Container(
                  height: appBarAlpha>0.2?0.5:0,
                  decoration: const BoxDecoration(
                    boxShadow: [BoxShadow(color: Colors.black12,blurRadius: 0.5)]
                  ),
                )
              ],
            )
          ],
        )
      ),
    );
  }
  Future<Null> _homesRefresh() async{
    await Future.delayed(const Duration(milliseconds: 200));
    return null;
  }
  _jumpSearch(){
    NavigatorUtil.push(context, const SearchPage());
  }
  _jumpSpeak(){
    NavigatorUtil.push(context, SpeaksPage());
  }
}
